package Fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import Database.SQLquery;
import barcode.code.nhat.iuhbarcode.Main_Action;
import barcode.code.nhat.iuhbarcode.R;

import static android.widget.Toast.makeText;

public class Excel_Fragment extends Fragment {

    private static final String ARG_SECTION_NUMBER = "section_number";

    public static Excel_Fragment newInstance(int sectionNumber) {
        Excel_Fragment fragment = new Excel_Fragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public Excel_Fragment() {
    }



    private Spinner sp1,sp2;
    public static int pos;
    private String[] Titles;
    private Button b1,b2;
    private TextView t1;
    private EditText e1;
    private SQLquery login;
    private String name_class;
    String nametoexport;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View zx = inflater.inflate(R.layout.fragment_excel, container, false);
        login = new SQLquery(getActivity());
        login = login.open();

        sp2 = (Spinner) zx.findViewById(R.id.spinner_class);

        List<String> per = login.get_table_check();
        ArrayAdapter<String> Adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, per);
        sp2.setAdapter(Adapter);
        sp2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                name_class = String.valueOf(parent.getItemAtPosition(position));
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        t1 = (TextView) zx.findViewById(R.id.txt_congra);
        b2 = (Button) zx.findViewById(R.id.bt_link);


        e1 = (EditText) zx.findViewById(R.id.ed_excel_name);


        b1 = (Button) zx.findViewById(R.id.bt_export);
        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                nametoexport = String.valueOf(e1.getText());
                final String boss = "/sdcard/" + nametoexport + ".xls";
                b2.setText(boss);
                if(nametoexport.equals("")){
                    e1.setError("Please input file name!");
                }else{
                    t1.setVisibility(View.VISIBLE);
                    b2.setVisibility(View.VISIBLE);
                    creater_xls(boss, name_class);

                }

                b2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        openFolder(boss);
                    }
                });

            }
        });



        return zx;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((Main_Action) activity).onSectionAttached(getArguments().getInt(ARG_SECTION_NUMBER));
    }


    @SuppressLint("SdCardPath")
    public void openFolder(String name)
    {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri = Uri.parse("file://"+name);
        intent.setDataAndType(uri, "application/vnd.ms-excel");
        startActivity(intent);
    }

    /*public void creater_xlsx(String name,String classname){
        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFCell c = null;

        XSSFCellStyle cs = wb.createCellStyle();
        cs.setAlignment(XSSFCellStyle);
        cs.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
        cs.setFillForegroundColor(HSSFColor.LIME.index);
        cs.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

        XSSFCellStyle cs1 = (XSSFCellStyle) wb.createCellStyle();
        cs1.setAlignment(CellStyle.ALIGN_CENTER);
        cs1.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
        cs1.setFillForegroundColor(HSSFColor.BLUE_GREY.index);
        cs1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

        XSSFSheet sheet = null;
        sheet = (XSSFSheet) wb.createSheet();
        XSSFRow row = sheet.createRow(0);

        //Tieu muc o thu nhat cua hang(row) dau tien tuong ung la gia tri row(0)
        c = row.createCell(0);
        c.setCellValue("STT");
        c.setCellStyle(cs);

        //tieu muc o thu hai row(0)
        c = row.createCell(1);
        c.setCellValue("Ho Ten");
        c.setCellStyle(cs);

        //tieu muc o thu ba row(0)
        c = row.createCell(2);
        c.setCellValue("MSSV");
        c.setCellStyle(cs);

        //tieu muc o thu ba row(0)
        c = row.createCell(3);
        c.setCellValue("So Tiet");
        c.setCellStyle(cs);

        //tieu muc o thu tu row(0)
        c = row.createCell(4);
        c.setCellValue("Ngay Diem Danh");
        c.setCellStyle(cs1);

        //kich co cua cac cot(cell)
        sheet.setColumnWidth(0, (15 * 100));
        sheet.setColumnWidth(1, (15 * 350));
        for (int i = 2; i < 10; i++)
            sheet.setColumnWidth(i, (15 * 250));

        // buoc cuoi cung la tao file
        File file = new File(name);
        FileOutputStream os = null;
        try {
            os = new FileOutputStream(file);
            wb.write(os);
            makeText(getActivity(), "File excel had created!", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            makeText(getActivity(), "Create file is ERROR!", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            makeText(getActivity(), "Failed to save file!", Toast.LENGTH_SHORT).show();
        } finally {
            try {
                if (null != os)
                    os.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }*/
    public void creater_xls(String name,String classname){
        Workbook wb = new HSSFWorkbook();
        Cell c = null;

        //Cell style for header row
        CellStyle cs = wb.createCellStyle();
        cs.setAlignment(CellStyle.ALIGN_CENTER);
        cs.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
        cs.setFillForegroundColor(HSSFColor.LIME.index);
        cs.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

        CellStyle cs1 = wb.createCellStyle();
        cs1.setAlignment(CellStyle.ALIGN_CENTER);
        cs1.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
        cs1.setFillForegroundColor(HSSFColor.BLUE_GREY.index);
        cs1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

        //New Sheet
        Sheet sheet1 = null;
        sheet1 = wb.createSheet(classname);
        //sheet1.addMergedRegion(new CellRangeAddress(*//*row*//* 0, 0,*//*column*//*2, 9));
        // Generate column headings
        Row row = sheet1.createRow(0);

        //Tieu muc o thu nhat cua hang(row) dau tien tuong ung la gia tri row(0)
        c = row.createCell(0);
        c.setCellValue("STT");
        c.setCellStyle(cs);

        //tieu muc o thu hai row(0)
        c = row.createCell(1);
        c.setCellValue("Ho Ten");
        c.setCellStyle(cs);

        //tieu muc o thu ba row(0)
        c = row.createCell(2);
        c.setCellValue("MSSV");
        c.setCellStyle(cs);

        //tieu muc o thu ba row(0)
        c = row.createCell(3);
        c.setCellValue("So Tiet");
        c.setCellStyle(cs);

        //tieu muc o thu tu row(0)
        c = row.createCell(4);
        c.setCellValue("Ngay Diem Danh");
        c.setCellStyle(cs1);

        //kich co cua cac cot(cell)
        sheet1.setColumnWidth(0, (15 * 100));
        sheet1.setColumnWidth(1, (15 * 350));
        for (int i = 2; i < 14; i++)
            sheet1.setColumnWidth(i, (15 * 250));

        // buoc cuoi cung la tao file
        File file = new File(name);
        FileOutputStream os = null;

        try {
            os = new FileOutputStream(file);
            wb.write(os);
            makeText(getActivity(), "File excel had created!", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            makeText(getActivity(), "Create file is ERROR!", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            makeText(getActivity(), "Failed to save file!", Toast.LENGTH_SHORT).show();
        } finally {
            try {
                if (null != os)
                    os.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}
